﻿#region Copyright
/* © 2008 George Tsiokos, licensed under the Microsoft Reciprocal License (Ms-RL) */
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Comet.Timers {
    public sealed class TimeTimer {

		#region Fields (3) 

        private readonly Action _callback;
        private readonly TimeInterval _timeInterval;
        private readonly Timer _timer;

		#endregion Fields 

		#region Constructors (1) 

        public TimeTimer (TimeInterval timeInterval, Action callback) {
            _timeInterval = timeInterval;
            _callback = callback;
            _timer = new Timer (Callback);
        }

		#endregion Constructors 

		#region Methods (4) 


		// Public Methods (2) 

        public void Start () {
            StartTimer ();
        }

        public void Stop () {
            _timer.Change (-1, -1);
        }



		// Private Methods (2) 

        private void Callback (object state) {
            try {
                _callback.Invoke ();
            }
            finally {
                StartTimer ();
            }
        }

        private void StartTimer () {
            DateTime dateTime = DateTime.UtcNow;
            int interval;
            switch (_timeInterval) {
                case TimeInterval.Second:
                    interval = 1000 - dateTime.Millisecond;
                    break;
                case TimeInterval.Minute:
                    interval = 60000 - (dateTime.Second * 1000);
                    break;
                case TimeInterval.Hour:
                    interval = 3600000 - (dateTime.Minute * 60000);
                    break;
                case TimeInterval.Day:
                    interval = 86400000 - (dateTime.Hour * 3600000);
                    break;
                default:
                    throw new NotSupportedException ();
            }
            _timer.Change (interval, -1);
        }


		#endregion Methods 

    }
}